class Project < ActiveRecord::Base
  has_many :tickets
  
  has_and_belongs_to_many :categories, :order => 'name DESC'
  
  validates_presence_of     :name   
  validates_length_of       :name,    :within => 3..40
  def users
    u = User.find(:all, :order => 'login DESC')
    users = Array.new
    for user in u
      if user.has_role?(self.name + '_member') && !user.has_role?('admin') && !user.has_role?(self.name + '_admin')
        users << user
      end
    end
    return users
  end
  
  def admins
    u = User.find(:all, :order => 'login DESC')
    users = Array.new
    for user in u
      if user.has_role?(self.name + '_admin')
        users << user
      end
    end
    return users
  end
  
  def members
    u = User.find(:all, :order => 'login DESC')
    users = Array.new
    for user in u
      if user.has_role?(self.name + '_member') || user.has_role?(self.name + '_admin')
        users << user
      end
    end
    return users
  end
  
  def closed_tickets
    tickets = []
    for ticket in self.tickets
      if ticket.status == Ticket.states['approved'] || ticket.status == Ticket.states['finished'] || ticket.status == Ticket.states['wont_fix'] || ticket.status == Ticket.states['unrepairable']
        tickets << ticket
      end
    end
    
    return tickets
  end
  
  def closed_tickets_last_week
    tickets = []
    for ticket in Ticket.find(:all, :conditions => ["updated_at > ? AND project_id= " + self.id.to_s, (Date.today-7)])
      if (ticket.status == Ticket.states['approved'] || ticket.status == Ticket.states['finished'] || ticket.status == Ticket.states['wont_fix'] || ticket.status == Ticket.states['unrepairable']) 
        tickets << ticket
      end
    end
    
    return tickets
  end
  
  def open_tickets
    tickets = []
    for ticket in self.tickets
      if ticket.status != Ticket.states['approved'] && ticket.status != Ticket.states['finished'] && ticket.status != Ticket.states['wont_fix'] && ticket.status != Ticket.states['unrepairable']
        tickets << ticket
      end
    end
    
    return tickets
  end
  
  def edit_states(user)
    st = Ticket.states
    states = Array.new
    for state in st
      if state[1] == Ticket.states['approved'] || state[1] == Ticket.states['not_approved']
        if user.has_role?(self.name+'_admin') 
          states << state
        end
      else
        states << state
      end
    end
    return states
  end
    
    
  def procent_closed
    if self.closed_tickets.length > 0 && self.tickets.count > 0 
      return self.closed_tickets.length * 100 / self.tickets.count
    else
      return 0;
    end
  end
end
